#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：back 
@File    ：article_svc.py
@IDE     ：PyCharm 
@Author  ：七分是你
@Date    ：2024/7/13 下午1:46 
@explain : 
"""
import time

from fastapi import Request

from app import dao
from app import utils
from app.types.appproto import ArticleData


class ArticeService:
    @classmethod
    def get_artice_list(cls, cid: int = 0, page: int = 1, page_size: int = 10,
                        request: Request = None) -> utils.HttpResponse:
        where = {'is_display': 1}
        if cid > 0:
            where['cid'] = cid
        where['addtime'] = ['lt', int(time.time())]
        total, result = dao.ArticleQueryDao.list(
            field_names=['id', 'title', 'seo_description', 'seo_keywords', 'thumb', 'link_url', 'click', 'addtime',
                         'source_reprint'],
            page=page, page_size=page_size, **where)
        if total == 0:
            return utils.ResponseSuccess(None)
        records_list = []
        for record in result:
            parent_records = {'id': record.id, 'title': record.title, 'description': record.seo_description,
                              'thumb': record.thumb, 'link_url': record.link_url, 'keywords': record.seo_keywords,
                              'click': record.click,
                              'addtime': utils.StringUtil.format_timestamp_to_str(record.addtime, '%Y-%m-%d'),
                              'source': record.source_reprint}
            records_list.append(parent_records)
        return utils.ResponseSuccess({"total": total, "records": records_list})

    @classmethod
    def get_article_by_id(cls, id: int, request: Request = None) -> utils.HttpResponse:
        result = dao.ArticleQueryDao.find_by_id(id)
        if result:
            data = ArticleData(id=result.id, title=result.title, seo_description=result.seo_description,
                               content=result.content,
                               seo_keywords=result.seo_keywords,
                               attach=result.attach, thumb=result.thumb, link_url=result.link_url, click=result.click,
                               addtime_str=utils.StringUtil.format_timestamp_to_str(result.addtime, '%Y-%m-%d'),
                               source_reprint=result.source_reprint)
            return utils.ResponseSuccess(data)
        else:
            return utils.ResponseFail('内容ID错误')
